/**
 * Created with hong.rong
 * Date:2020/07/01
 */

import React, { useState, useCallback, Fragment } from 'react'
import { history } from 'umi'
import { isFunction } from 'lodash'
import { Modal, Form, Input, message } from 'antd'
import { STORATE_KEY } from '@/constant'
import { updatePwd } from '@/services/login'

export default function ModifyPwd({ children }) {
  const [visible, setVisible] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false)
  const [form] = Form.useForm()

  const handleOk = useCallback(() => {
    form.validateFields().then(async values => {
      setConfirmLoading(true)
      const userInfo = JSON.parse(
        localStorage.getItem(STORATE_KEY.USER_INFO) || '{}'
      )
      values.adminId = userInfo.adminId
      const { data = {} } = await updatePwd(values)
      if (data && data.code === 0) {
        message.success('修改密码成功')
        localStorage.clear()
        history.replace({ pathname: '/login' })
        setConfirmLoading(false)
      } else {
        setConfirmLoading(false)
      }
    })
  }, [])

  const handleShow = useCallback(() => {
    setVisible(true)
  }, [])

  const handleCancel = useCallback(() => {
    setVisible(false)
    setConfirmLoading(false)
    form.resetFields()
  }, [])

  return (
    <Fragment>
      {isFunction(children) && children(handleShow)}
      <Modal
        destroyOnClose
        title="修改密码"
        visible={visible}
        confirmLoading={confirmLoading}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form labelAlign="left" form={form}>
          <Form.Item
            label="新密码"
            name="adminPwd"
            rules={[{ required: true }]}
          >
            <Input.Password placeholder="请输入" />
          </Form.Item>
        </Form>
      </Modal>
    </Fragment>
  )
}
